package com.baimsg.museum;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Security;
import java.util.Base64;

public class AES256 {

    static {
        if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
            Security.addProvider(new BouncyCastleProvider());
        }
    }

    public static String encrypt(String key, String src) {
        if (key != null) {
            try {
                if (!key.isEmpty() && src != null && !src.isEmpty()) {
                    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
                    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
                    byte[] bytes = src.getBytes(StandardCharsets.UTF_8);
                    cipher.init(1, secretKeySpec);
                    return byte2Base64(cipher.doFinal(bytes));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String encryptPKCS5(String key, String src) {
        if (key != null) {
            try {
                if (!key.isEmpty() && src != null && !src.isEmpty()) {
                    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
                    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
                    byte[] bytes = src.getBytes(StandardCharsets.UTF_8);
                    cipher.init(1, secretKeySpec);
                    return byte2Base64(cipher.doFinal(bytes));
                }
            } catch (Exception ignored) {
            }
        }
        return null;
    }

    private static String byte2Base64(byte[] bytes) {
        try {
            return Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            return null;
        }
    }

}
